import 'dart:async';
import 'dart:math';

import 'package:cave_flutter/common/common_widget.dart';
import 'package:cave_flutter/network/whl_api.dart';
import 'package:cave_flutter/pages/cave/cave_setting/cave_admin_privileges/cave_admin_privileges_model.dart';
import 'package:cave_flutter/pages/cave/cave_setting/cave_master_per_detail_model.dart';
import 'package:cave_flutter/pages/whl_home/whl_publish/push_top_setting/push_top_setting_sheet.dart';
import 'package:cave_flutter/utils/whl_toast_utils.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:extended_nested_scroll_view/extended_nested_scroll_view.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_barrage/flutter_barrage.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../../model/dynamic_model.dart';
import '../../../routes/whl_app_pages.dart';
import '../../../style/whl_style.dart';
import '../../../widgets/brick/widget/basic_widget.dart';
import '../../../widgets/brick/widget/image_widget.dart';
import '../../../widgets/brick/widget/text_widget.dart';
import './model/cave_model.dart';

class Cave_detailLogic extends GetxController {
  EasyRefreshController refreshController = EasyRefreshController(
      controlFinishRefresh: true, controlFinishLoad: true);
  //  群主权限
  CaveMasterPerDetailModel masterPerDetailModel = CaveMasterPerDetailModel();
  //  管理员权限
  CaveAdminPrivilegesModel adminPrivilegesModel = CaveAdminPrivilegesModel();

  List tabList = ["最新", "精华", "Cave群主贴"];

  BarrageWallController barrageWallController = BarrageWallController();

  int caveId = 0;

  CaveModel caveDetail = CaveModel();

  String createDays = '';
  //  3群主 1管理员 2普通成员
  int caveRole = 0;

  List listData = [];
  int size = 10;
  int current = 1;
  int selectedTabIndex = 0;

  bool noticeMaximize = false;

  @override
  void onInit() {
    super.onInit();
    var arguments = Get.arguments;
    if (arguments != null) {
      caveId = arguments['id'];
    }
    starBarrage();
    getCaveRole();
    getCaveDetail();
    loadSquareData(isRefresh: true);

    // update();
  }

  getCaveDetail() async {
    ResponseData responseData =
        await WhlApi.getCaveDetail.get({'caveId': caveId});

    if (responseData.isSuccess()) {
      caveDetail = CaveModel.fromJson(responseData.data);
      update();
    }
    getDateDays();
  }

  getDateDays() {
    DateTime givenTime = DateTime.parse(caveDetail.createDate.toString());
    DateTime currentTime = DateTime.now();

    Duration duration = currentTime.difference(givenTime);

    createDays = duration.inDays.toString();
    update();
  }

  void getMasterPerDetail() async {
    ResponseData responseData =
        await WhlApi.getMasterPerDetail.get({'caveId': caveId});
    if (responseData.isSuccess()) {
      if (responseData.data != null) {
        masterPerDetailModel =
            CaveMasterPerDetailModel.fromJson(responseData.data);
      }
      update();
    } else {
      MyToast.show(responseData.msg ?? '获取群主设置信息失败');
    }
  }

  void getAdminPrivileges() async {
    ResponseData responseData =
        await WhlApi.getAdminPerDetail.get({'caveId': caveId});
    if (responseData.isSuccess()) {
      if (responseData.data != null) {
        adminPrivilegesModel =
            CaveAdminPrivilegesModel.fromJson(responseData.data);
      }
      update();
    } else {
      MyToast.show(responseData.msg ?? '获取管理员设置信息失败');
    }
  }

  getCaveRole() async {
    getMasterPerDetail();
    getAdminPrivileges();
    ResponseData responseData =
        await WhlApi.getRoleInCave.get({'caveId': caveId});

    if (responseData.isSuccess()) {
      if (responseData.data['isAdmin'] == 1) {
        caveRole = 1;
      }

      if (responseData.data['isGuest'] == 1) {
        caveRole = 2;
      }

      if (responseData.data['isMaster'] == 1) {
        caveRole = 3;
      }

      update();
    }
  }

  void pushTopSetting(DynamicModel model) {
    Get.bottomSheet(
      PushTopSettingSheet(
        id: model.id,
        dataSource: DynamicDataSource.Cave,
      ),
      isScrollControlled: true,
    ).then((value) {
      if (value['num'] != null) {
        model.topOrder = 4;
      }
      update();
    });
  }

  loadSquareData({bool isRefresh = false}) async {
    if (isRefresh) {
      current = 1;
    } else {
      current++;
    }
    Map<String, dynamic> param = {
      "size": size,
      "current": current,
      "type": selectedTabIndex + 1,
      "caveId": caveId
    };

    ResponseData responseData = await WhlApi.getCaveSquareList.get(param);
    if (responseData.isSuccess()) {
      List records = responseData.data["records"];
      List<DynamicModel> modelList =
          records.map((e) => DynamicModel.fromJson(e)).toList();
      if (isRefresh) {
        listData = modelList;
        refreshController.finishRefresh();
        refreshController.resetFooter();
      } else {
        listData.addAll(modelList);
        refreshController.finishLoad();
      }
      if (records.length < size) {
        refreshController.finishLoad(IndicatorResult.noMore);
      }
      update();
    } else {
      current--;
      refreshController.finishRefresh();
      refreshController.finishLoad();
      update();
    }
  }

  Future<void> toSendPage() async {
    var a =
        await Get.toNamed(Routes.addCavePost, arguments: {'caveId': caveId});
    print('toSendPage---------');
    print(a);
    if (a != null) {
      refreshController.callRefresh();
    }
  }

  toCaveGroup() {
    if (caveDetail.id != null) {
      Get.toNamed(Routes.caveGroupChat, arguments: {
        'id': caveDetail.id,
        'tid': caveDetail.tid,
        'type': caveDetail.caveType,
        'caveName': caveDetail.caveName,
        'showName': 'showName',
      });
    }
  }

  starBarrage() {
    Random random = Random();
    int count = 0;
    Timer.periodic(const Duration(seconds: 1), (timer) {
      int ran = random.nextInt(60000);
      barrageWallController.send([createBullet(index: ran)]);
      count++;
      if (count >= 20) {
        timer.cancel();
      }
    });
  }

  Bullet createBullet({int? index}) {
    return Bullet(
      showTime: Random().nextInt(60000),
      child: UIContainer(
          height: 35.w,
          padding: EdgeInsets.only(bottom: 5.w, right: 5.w),
          child: UIRow(
            radius: 15.w,
            mainAxisSize: MainAxisSize.min,
            color: kAppColor("#F0F0F0"),
            children: [
              UIImage(
                margin: EdgeInsets.only(
                  left: 10.w,
                  right: 5.w,
                ),
                assetImage: "icon_home_top_2",
                width: 15.w,
                height: 15.w,
              ),
              UIText(
                margin: EdgeInsets.only(right: 10.w),
                text: "5分钟前发布了新帖 $index",
                fontSize: 11.sp,
                textColor: kAppWhiteColor,
              )
            ],
          )),
    );
  }
}
